<template>
  <div class="front shopProduct docWidth">
    <div class="productBox">
      <div class="imgs">
        <SwiperPiczoom :imgs="detail.images" />
      </div>
      <div class="product">
        <div class="name">
          <p>{{detail.name}}</p><span @click="beforeCheck(1)">{{detail.isCollect ? '取消收藏' : '收藏商品'}}</span>
        </div>
        <div class="price" v-if="userInfo.status === 1">
          商品价格：&nbsp;&nbsp;<span >{{showInfoData.priceText}}</span></div>
        <div v-else style="width: 154px;">
          <PriceInfo></PriceInfo>
        </div>
        <el-row style="margin-top:17px;">
          <el-col :span="6" style="margin-top: 10px;">规格：</el-col>
          <el-col :span="18">
            <div class="skuList">
              <div :class="['skuItem',skuIndex === index ? 'on' : '']" v-for="(item,index) in detail.skuList"
                :key="index" @click="changeSku(index)">{{item.name}}</div>
            </div>
          </el-col>
        </el-row>
        <el-row style="margin-top:17px;">
          <el-col :span="6" style="margin-top: 10px;">数量：</el-col>
          <el-col :span="8">
            <el-input-number v-model="operationNum" :min="1" controls-position="right" size="small"></el-input-number>
          </el-col>
          <!-- <el-col :span="2" style="margin-top:10px;">{{detailUnit}}</el-col> -->
        </el-row>
        <!-- <el-row style="margin-top:20px;">
          <el-col :span="6">起订量：</el-col>
          <el-col :span="18">≥{{showInfoData.startNum}}{{detail.unit}}</el-col>
        </el-row> -->
        <el-row style="margin-top:17px;">
          <el-col :span="6">成交：</el-col>
          <el-col :span="18">{{showInfoData.saleNum}}</el-col>
        </el-row>
        <el-row style="margin-top:17px;">
          <el-col :span="6">发货地址：</el-col>
          <el-col :span="18">{{detail.startProvinceName}}{{detail.startCityName}}{{detail.startDistrictName}}</el-col>
        </el-row>
        <!-- <el-row style="margin-top:17px;">
          <el-col :span="6">物流费用：</el-col>
          <el-col :span="18">{{detail.logistics ? `${detail.logistics}元` : '免运费'}}</el-col>
        </el-row> -->
        <el-row style="margin-top:27px;" :gutter="30">
          <el-col :span="12">
            <div class="payBtn" @click="beforeCheck(4)">立即购买</div>
          </el-col>
          <!-- <el-col :span="12">
            <div class="payBtn join" @click="beforeCheck(3)">加入购物车</div>
          </el-col> -->
        </el-row>
      </div>
      <div class="tuijian">
        <div class="title">店铺热门推荐</div>
        <ul>
          <li v-for="(item,index) in hotProduct" :key="index" @click="toDetail(item.id)">
            <div class="image" :style="{backgroundImage:`url(${item.image})`}"></div>
            <div class="price" v-if="userInfo.status === 1">{{item.priceText!=='面议'?'￥':''}}<span>{{item.priceText}}</span></div>
            <div class="name">{{item.name}}</div>
            <!-- <div class="productShop">{{item.name}}</div> -->
          </li>
        </ul>
      </div>
    </div>
    <div class="productDetailBox">
      <div class="leftWarpper">
        <div class="shop">
          <div class="name">{{shopInfo.shopName}}</div>
          <el-row style="margin-top:17px;">
            <el-col :span="9">卖家：</el-col>
            <el-col :span="15">{{shopInfo.companyName}}</el-col>
          </el-row>
          <el-row style="margin-top:17px;font-size:15px">
            <el-col :span="9">所在地：</el-col>
            <el-col :span="15">
              {{shopInfo.companyProvinceName}}{{shopInfo.companyCityName}}{{shopInfo.companyDistrictName}}</el-col>
          </el-row>
          <!-- <el-row style="margin-top:17px;">
            <el-col :span="9">联系电话：</el-col>
            <el-col :span="15">{{shopInfo.mobile}}</el-col>
          </el-row> -->
          <el-row style="margin-top:17px;">
            <el-col :span="9">入驻时间：</el-col>
            <el-col :span="15">{{shopInfo.createTime | formatDate}}</el-col>
          </el-row>
        </div>
        <div class="tuijian">
          <div class="title">店铺最新推荐</div>
          <ul>
            <li v-for="(item,index) in newProduct" :key="index" @click="toDetail(item.id)">
              <div class="image" :style="{backgroundImage:`url(${item.image})`}"></div>
              <div class="good-title">{{item.name}}</div>
              <div class="price_warpper" v-if="userInfo.status === 1">
                <!-- <div>呱呱呱呱呱呱</div> -->
                <div class="price">{{item.priceText!=='面议'?'￥':''}}<span>{{item.priceText}}</span></div>
              </div>
              <PriceInfo v-else></PriceInfo>
            </li>
          </ul>
        </div>
      </div>
      <div class="detail">
        <el-tabs type="border-card">
          <el-tab-pane label="商品详情">
            <div v-html="detail.remark"></div>
          </el-tab-pane>
          <el-tab-pane label="商品评价">
            <!-- 商品评价 -->
            <ul class="infinite-list" v-infinite-scroll="load" style="overflow:auto">
               <li v-for="(item,index) in commentList" class="infinite-list-item">
                  <div class="content">
                    <img src="../../../../assets/logo.png" style="width: 60px;height: 60px;" />
                    <div class="content_tit">
                      <span> {{item.mobile}}</span>
                      <div class="rate">
                        <el-rate
                          v-model="item.productScore"
                          disabled
                          text-color="#ff9900"
                          score-template="{value}">
                        </el-rate>
                      </div>
                    </div>
                  </div>
                  <div class="content_text">
                    <span>{{item.content}}</span>
                  </div>
                 <!-- <div v-for="(item,index) in item.imgs" :key="index" :title="item.name || ''">
                    <el-image style="width: 220px; height: 220px" :src="item.image" :preview-src-list="[item.image]"></el-image>
                  </div> -->
               </li>
             </ul>

          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters, mapState } from 'vuex'
import { productPageByQo, productGetById, CommentList } from "@/api/front-home";
import { saveOrUpdate, confirm } from "@/api/cart";
import PriceInfo from "@/views/front/components/priceInfo.vue";
import SwiperPiczoom from './components/SwiperPiczoom/index'
export default {
  name: 'FrontShopProduct',
  components: { SwiperPiczoom, PriceInfo },
  filters: {
    formatDate(value) {
      if (!value) return ''
      return value.toString().split(' ')[0]
    }
  },
  data() {
    return {
      submitFlag: false,
      detail: {},
      hotProduct: [],
      newProduct: [],
      productId: '',
      skuIndex: -1,
      operationNum: 1,
      pagenum:10,
      pagesize:1,
      commentList:[],
      showInfoData: {
        productSkuId: null,
        startNum: 0,
        saleNum: 0,
        priceText: '',
        store: ''
      },
      shopId: 0,
      detailUnit: ''
    };
  },
  computed: {
    ...mapGetters(["userInfo","token"]),
    ...mapState({
      shopInfo: state => state.front.shopInfo,
    })
  },
  watch: {
    $route(val) {
      this.productId = this.$route.query && this.$route.query.productId && Number(this.$route.query.productId)
      this.getProductDetail()
    }
  },
  created() {
    this.shopId = this.$route.query && this.$route.query.id && Number(this.$route.query.id)
    this.productId = this.$route.query && this.$route.query.productId && Number(this.$route.query.productId)
    if (this.$store.state.front.shopId !== this.shopId) {
      this.$store.commit("front/SET_SHOPID", this.shopId)
      this.$store.dispatch('front/getShopInfo', this.shopId)
    }
    this.getProductDetail()
    this.getHotProduct(this.shopId)
    this.getnewProduct(this.shopId)
    if(this.token){
      this.CommentList()
    }

  },
  methods: {
    load () {
     this.pagesize ++
    },
    CommentList(){
      let {pagesize,pagenum} = this;
      CommentList({pagesize,pagenum,productId:this.productId}).then(res=>{
        console.log(res.records);
        let data = res.records.map(v => {
        	if (typeof v.imgs === 'string') {
        		v.imgs = v.imgs.split(',');
        	}
        	if (!v.imgs) {
        		v.imgs = [];
        	}
        	return v;
        });
        this.commentList = data;
      })
    },
    // 加入购物车
    addCart() {
      if (!this.showInfoData.productSkuId) {
        // this.$notify.warning({
        //   title: '温馨提示',
        //   message: '请选择规格！'
        // });

        this.$message({
          message: '请选择规格！',
          type: 'warning'
        });
        return
      }
      const detail = this.detail
      const params = {
        gongyingId: detail.gongyingId,
        num: this.operationNum,
        productId: detail.id,
        productSkuId: this.showInfoData.productSkuId
      }
      saveOrUpdate(params).then(res => {
        // this.$notify({
        //   title: '温馨提示',
        //   message: '加入购物车成功！',
        //   type: 'success'
        // });

        this.$message({
          message: '加入购物车成功！',
          type: 'success'
        });
      }).catch(err => {
				if(err=='Error: 账号未认证，请及时认证。'){
					this.$router.push({ path: '/company/info/name=Identification'});
					return
				}
      });
    },

    // 立即购买
    buy() {
      if (!this.showInfoData.productSkuId) {
        // this.$notify.warning({
        //   title: '温馨提示',
        //   message: '请选择规格！'
        // });

        this.$message({
          message: '请选择规格！',
          type: 'warning'
        });
        return
      }
      const detail = this.detail
      const params = {
        gongyingId: detail.gongyingId,
        num: this.operationNum,
        productId: detail.id,
        productSkuId: this.showInfoData.productSkuId
      }
      if (this.submitFlag) return;
      this.submitFlag = true
      confirm(params).then((res) => {
        const cartIds = res.countDTOS[0].detailList[0].cardId
        this.$router.push({ path: '/confirm-order', query: { cartIds } })
        this.submitFlag = false
      }).catch(err => {
				if(err=='Error: 账号未认证，请及时认证。'){
					this.$router.push({ path: '/company/info/name=Identification'})
				}
        this.submitFlag = false
      })
    },

    getHotProduct(id) {
      productPageByQo({ pageNo: 1, pageSize: 2, memberId: id, saleNum$sort: 'desc' }).then((res) => {
        this.hotProduct = res.list || []
      });
    },

    getnewProduct(id) {
      productPageByQo({ pageNo: 1, pageSize: 3, memberId: id, saleNum$sort: 'desc' }).then((res) => {
        this.newProduct = res.list || []
      });
    },
    getProductDetail() {
      productGetById(this.productId).then((res) => {
        this.detail = res || {}
        if (!this.detail.images) {
          this.detail.images = this.detail && this.detail.image
        }
        this.$set(this.showInfoData, 'startNum', this.detail.starNum || 0)
        this.$set(this.showInfoData, 'saleNum', this.detail.saleNum || 0)
        this.$set(this.showInfoData, 'priceText', this.detail.priceText || '')
        this.$set(this.showInfoData, 'store', this.detail.store || 0)
        if (this.detail.skuList.length > 0) {
          this.detailUnit = this.detail.skuList[0].unit || '';
        }
      });
    },
    toDetail(productId) {
      console.log(productId)
      this.$router.push({ path: '/front-shop/productDetail', query: { id: this.shopId, productId: productId } });
    },
    changeSku(index) {
      if (this.skuIndex === index) {
        return
      }
      this.skuIndex = index
      this.$set(this.showInfoData, 'productSkuId', this.detail.skuList[index].id || null)
      this.$set(this.showInfoData, 'startNum', this.detail.skuList[index].startNum || 0)
      // this.$set(this.showInfoData, 'saleNum', this.detail.skuList[index].saleNum || 0)
      this.$set(this.showInfoData, 'priceText', this.detail.skuList[index].priceText || '')
      this.$set(this.showInfoData, 'store', this.detail.skuList[index].store || 0)

      this.detailUnit = this.detail.skuList[index].unit || '';

      this.operationNum = this.detail.skuList[index].startNum
    },
    collect() {
      const params = {
        otherId: this.detail.id,
        type: 1
      }
      this.$store.dispatch('front/collect', params).then(() => {
        this.$message.success('操作成功')
        this.getProductDetail()
      }).catch(() => [
        this.$message.error('操作失败')
      ])
    },
    collect2() {
      const params = {
        otherId: this.shopId,
        type: 2
      }
      this.$store.dispatch('front/collect', params).then(() => {
        this.$message.success('操作成功')
        this.$store.dispatch('front/getShopInfo', this.shopId)
      }).catch(() => [
        this.$message.error('操作失败')
      ])
    },
    beforeCheck(type) {
      //type 1商品收藏，2店铺收藏，3加入购物车，4立即购买
      if (this.userInfo && this.userInfo.id) {
        switch (type) {
          case 1:
            this.collect()
            break;
          case 2:
            this.collect2()
            break;
          case 3:
            this.addCart()
            break;
          case 4:
            this.buy()
            break;
        }
      } else {
        this.$confirm('请登录后执行此操作').then(() => {
          this.$router.replace(`/login?redirect=${this.$route.fullPath}`)
        })
      }
    }
  },
};
</script>
<style lang="scss">
.shopProduct {
  .detail {
    img {
      max-width: 100%;
    }
    .content{
      width: 100%;
      display: flex;
      flex-direction: row;
      align-items: center;
    }
    .content_tit{
      flex: 1;
      display: flex;
      flex-direction: row;
      align-items: center;
      justify-content: space-between;
      padding: 0 20px;
      .rate{
      }
    }
  }
}
</style>
<style lang="scss" scoped>
.shopProduct {
  .productBox {
    margin-top: 30px;
    display: flex;
    .imgs {
      width: 430px;
    }
    .product {
      flex: 1;
      margin: 0 36px;
      .name {
        line-height: 1.5;
        font-size: 18px;
        color: #000;
        display: flex;
        p {
          flex: 1;
        }
        span {
          padding-left: 10px;
          font-size: 16px;
          color: #ff9c00;
          cursor: pointer;
        }
      }
      .payBtn {
        line-height: 44px;
        font-size: 18px;
        color: #fff;
        background: #965f29;
        width: 187px;
        text-align: center;
        cursor: pointer;
        border-radius: 2px;
        &.join {
          box-sizing: border-box;
          background: #fff;
          border: 1px solid #965f29;
          color: #965f29;
        }
      }
      .price {
        margin-top: 17px;
        padding: 0 22px;
        line-height: 54px;
        font-size: 16px;
        color: #000;
        background: #e9e9e9;
        span {
          color: #FF4400;
        }
      }
      .skuList {
        overflow: hidden;
        .skuItem {
          float: left;
          padding: 6px 16px;
          font-size: 15px;
          font-weight: 300;
          color: #000;
          line-height: 2;
          cursor: pointer;
          margin: 0 10px 10px 0;
          border: 1px solid #b7b7b7;
          &.on {
            color: #965f29;
            border-color: #965f29;
          }
        }
      }
    }
    .tuijian {
      width: 270px;
      box-sizing: border-box;
      padding: 0 30px;
      border: 1px solid #e5e5e5;
      .title {
        line-height: 41px;
        font-size: 16px;
        color: #000000;
        padding: 6px 0;
      }
      ul {
        li {
          cursor: pointer;
          padding-bottom: 25px;
          .image {
            background-position: center;
            background-size: cover;
            background-repeat: no-repeat;
            height: 160px;
            border: 1px solid #e5e5e5;
          }
          .name {
            padding-top: 15px;
            line-height: 1.3;
            font-size: 18px;
            font-weight: 400;
            color: #000;
          }
          .price {
            margin-top: -33px;
            line-height: 33px;
            font-size: 14px;
            color: #FF4400;
            text-align: center;
            background: rgba(255, 255, 255, 0.5);
            span {
              font-size: 20px;
            }
          }
          .productShop {
            line-height: 1.3;
            font-size: 14px;
            font-weight: 400;
            color: #555;
          }
        }
      }
    }
  }
  .productDetailBox {
    display: flex;
    margin-top: 50px;
    .leftWarpper {
      width: 270px;
      .shop {
        box-sizing: border-box;
        border: 1px solid #e5e5e5;
        padding: 28px 24px;
        .name {
          font-size: 18px;
          color: #000;
        }
      }
      .tuijian {
        margin-bottom: 25px;
        margin-top: 25px;
        .title {
          background: #000000;
          line-height: 41px;
          font-size: 16px;
          color: #fff;
          padding: 0 32px;
        }
        ul {
          padding: 20px 20px 0;
          border: 1px solid #e5e5e5;
          li {
            cursor: pointer;
            padding-bottom: 25px;
            .image {
              background-position: center;
              background-size: cover;
              background-repeat: no-repeat;
              height: 210px;
              border: 1px solid #e5e5e5;
            }
            .name {
              padding-top: 15px;
              line-height: 1.3;
              font-size: 18px;
              font-weight: 400;
              color: #000;
            }
            .price_warpper {
              padding-top: 7px;
              font-size: 14px;
              font-weight: 400;
              color: #555;
              display: flex;
              justify-content: space-between;
            }
            .price {
              white-space: nowrap;
              font-size: 12px;
              color: #FF4400;
              span {
                font-size: 20px;
                height: 22px;
                line-height: 22px;
              }
            }
          }
        }
      }
    }
    .detail {
      margin-left: 30px;
      flex: 1;
      overflow: hidden;
    }
  }
}
</style>
